import utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/buyNow")
public class BuyNowServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String goodsId = request.getParameter("id"); // 获取商品ID
        String quantity = "1"; // 假设每次购买一件商品

        Connection connection = null;
        PreparedStatement stmtSelect = null;
        PreparedStatement stmtInsert = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection(); // 获取数据库连接

            // 查询商品信息
            String sqlSelect = "SELECT goods_name, unitprice FROM goods WHERE goods_id = ?";
            stmtSelect = connection.prepareStatement(sqlSelect);
            stmtSelect.setString(1, goodsId);
            rs = stmtSelect.executeQuery();

            String productName = "";
            double unitPrice = 0;
            if (rs.next()) { // 如果查询结果存在
                productName = rs.getString("goods_name");
                unitPrice = rs.getDouble("unitprice");
            } else {
                // 处理商品不存在的情况，例如抛出异常或设置错误消息
                throw new ServletException("商品不存在");
            }

            // 插入订单详情
            String sqlInsert = "INSERT INTO order_details (product_name, product_code, unit_price, quantity, is_delivered) VALUES (?, ?, ?, ?, 0)";
            stmtInsert = connection.prepareStatement(sqlInsert);
            stmtInsert.setString(1, productName);
            stmtInsert.setString(2, goodsId);
            stmtInsert.setDouble(3, unitPrice);
            stmtInsert.setInt(4, Integer.parseInt(quantity));
            stmtInsert.executeUpdate(); // 执行插入操作

            response.sendRedirect("buy.jsp"); // 购买成功后跳转的页面
        } catch (SQLException e) {
            throw new ServletException("Database access error", e);
        } finally {
            JDBCUtils.close(stmtInsert, connection); // 关闭资源
        }
    }
}